package com.mdinic.blogovi.service;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Service;

import com.mdinic.blogovi.model.Person;

/**
 * Extends {@link ShaPasswordEncoder} and initialize it with
 * {@link #ENCODING_BITS_256}.
 * 
 * @author mdinic
 * 
 */
@Service
public class PasswordService extends ShaPasswordEncoder {

    // 1 digit, 1 lower, 1 upper, from 6 to 20
    private static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";

    private static final Pattern PATTERN = Pattern.compile(PASSWORD_PATTERN, Pattern.DOTALL);

    /**
     * value of SHA strength.
     */
    private static final int ENCODING_BITS_256 = 256;

    /**
     * Constructor.
     */
    public PasswordService() {
        super(ENCODING_BITS_256);

    }

    /**
     * Produces encoded password.
     * 
     * @param salt
     * @param password
     * 
     * @return encoded password
     */
    public String createEncodedPassword(String salt, String password) {
        return encodePassword(password, salt);
    }

    public boolean isPasswordStrong(String rawPassword) {
        Matcher matcher = PATTERN.matcher(rawPassword);
        return matcher.matches();
    }

    public String generateConfirmCode(Person person) {
        return person.getFirstname().trim().charAt(0) + person.getLastname().trim().charAt(0)
                + UUID.randomUUID().toString().replace("-", "");
    }

    public String generatePassword() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 10);
    }

    public String generateToken() {
        return UUID.randomUUID().toString().replace("-", "A");
    }
}
